package vip.xiaonuo.biz.modular.edumaterialcate.manager;

import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.modular.educoursecate.entity.EduCourseCate;
import vip.xiaonuo.biz.modular.edumaterialcate.entity.EduMaterialCate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EduMaterialCateManager {

    /**
     * 封装树
     * @param allNodes
     * @return
     */
    public List<EduMaterialCate> buildTree(List<EduMaterialCate> allNodes) {
        // 1. 按父ID分组（pid作为key）
        Map<String, List<EduMaterialCate>> nodeMap = allNodes.stream()
                .collect(Collectors.groupingBy(EduMaterialCate::getPid));

        // 2. 获取顶层节点（pid="0"）
        List<EduMaterialCate> rootNodes = nodeMap.getOrDefault("0", new ArrayList<>());

        // 3. 递归构建子树
        for (EduMaterialCate root : rootNodes) {
            buildChildNodes(root, nodeMap);
        }

        return rootNodes;
    }

    /**
     * 构建子节点
     * @param parentNode
     * @param nodeMap
     */
    private void buildChildNodes(EduMaterialCate parentNode, Map<String, List<EduMaterialCate>> nodeMap) {
        // 1. 获取当前节点的所有子节点
        List<EduMaterialCate> children = nodeMap.get(parentNode.getId());
        if (children == null) return;

        // 2. 设置子节点列表
        parentNode.setChildren(children);

        // 3. 递归处理每个子节点
        for (EduMaterialCate child : children) {
            buildChildNodes(child, nodeMap);
        }
    }
}
